package com.codemart.lanze.modules.admin;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codemart.lanze.common.annotation.OperationLog;
import com.codemart.lanze.common.base.controller.AdminBaseController;
import com.codemart.lanze.common.security.token.FormToken;
import com.codemart.lanze.common.validator.group.Create;
import com.codemart.lanze.common.validator.group.Update;
import com.codemart.lanze.modules.cms.entity.Content;
import com.codemart.lanze.modules.cms.entity.ContentCat;
import com.codemart.lanze.modules.cms.service.IContentCatService;
import com.codemart.lanze.modules.cms.service.IContentService;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 内容
 * @Author: lanze
 * @Date: 2019-09-13
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "内容")
@Controller
@RequestMapping("/admin/content")
public class ContentController extends AdminBaseController {

	@Autowired
	private IContentService contentService;

	@Autowired
	private IContentCatService contentCatService;

	private static final String BASE_PATH = "admin/content/";

	@Value("${imageUrl}")
	public String IMAGE_URL;

	/**
	 * 分页查询内容列表
	 *
	 * @param pageNum
	 *            当前页码
	 * @param name
	 *            内容-查询关键字
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @param modelMap
	 * @return
	 */
	@RequiresPermissions("content:list")
	@GetMapping
	public String list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, Long contentCatId,
			String searchKey, String startTime, String endTime, ModelMap modelMap) throws Exception {
		try {
			log.debug("分页查询内容列表参数! pageNum = {}, contentCatId = {}, searchKey = {},  startTime = {}, endTime = {}",
					pageNum, contentCatId, searchKey, startTime, endTime);

			QueryWrapper<Content> ew = new QueryWrapper<>();
			ew.eq("content_cat_id", contentCatId);

			IPage<Content> iPage = contentService.page(new Page<>(pageNum, PAGESIZE), ew);

			ContentCat contentCat = new ContentCat();
			if (null != contentCatId) {
				contentCat = contentCatService.getById(contentCatId);
			}
			modelMap.put("contentCat", contentCat);

			log.info("分页查询内容列表结果！ pageInfo = {}", iPage);

			modelMap.put("pageInfo", iPage);
			modelMap.put("name", searchKey);
			modelMap.put("startTime", startTime);
			modelMap.put("endTime", endTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BASE_PATH + "content-list";
	}

	/**
	 * 根据主键ID删除内容
	 *
	 * @param id
	 * @return
	 */
	@OperationLog(value = "删除内容")
	@RequiresPermissions("content:delete")
	@DeleteMapping(value = "/content/{id}")
	public ResponseEntity<String> delete(@PathVariable("id") Long id) {
		log.debug("删除内容! id = {}", id);

		Content content = contentService.getById(id);
		if (null == content) {
			log.info("删除的内容不存在! id = {}", id);
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("内容不存在!");
		}

		contentService.removeById(id);
		log.info("删除内容成功! id = {}", id);
		return ResponseEntity.ok("已删除!");
	}

	/**
	 * 跳转到内容添加页面
	 *
	 * @return
	 */
	@FormToken(save = true)
	@RequiresPermissions("content:create")
	@GetMapping(value = "/add")
	public String add(Long contentCatId, ModelMap modelMap) {

		if (null != contentCatId) {
			ContentCat contentCat = contentCatService.getById(contentCatId);
			modelMap.put("contentCat", contentCat);
		}
		return BASE_PATH + "content-add";
	}

	/**
	 * 添加内容
	 *
	 * @param content
	 * @return
	 */
	@FormToken(remove = true)
	@OperationLog(value = "添加内容")
	@RequiresPermissions("content:create")
	@ResponseBody
	@PostMapping
	public ModelMap saveAdvertPosition(@Validated({ Create.class }) Content content) {
		ModelMap messagesMap = new ModelMap();

		log.debug("添加内容参数! content = {}", content);

		// 执行保存
		contentService.save(content);
		log.info("添加内容成功! contentId = {}", content.getId());
		messagesMap.put("status", SUCCESS);
		messagesMap.put("message", "添加成功!");
		return messagesMap;
	}

	/**
	 * 跳转到内容编辑页面
	 *
	 * @return
	 */
	@FormToken(save = true)
	@RequiresPermissions("content:update")
	@GetMapping(value = "/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap modelMap) throws Exception {
		log.debug("跳转到编辑内容信息页面参数! id = {}", id);
		Content content = contentService.getById(id);

		if (null != content) {
			ContentCat contentCat = contentCatService.getById(content.getContentCatId());
			modelMap.put("contentCat", contentCat);
		}

		log.info("跳转到编辑内容信息页面成功!, id = {}", id);
		modelMap.put("model", content);
		return BASE_PATH + "content-edit";
	}

	/**
	 * 更新内容信息
	 *
	 * @param id
	 * @param content
	 * @return
	 */
	@FormToken(remove = true)
	@OperationLog(value = "编辑内容")
	@RequiresPermissions("content:update")
	@ResponseBody
	@PutMapping(value = "/{contentId}")
	public ModelMap updateAdvertPosition(@PathVariable("contentId") Long contentId,
			@Validated({ Update.class }) Content content) {
		ModelMap messagesMap = new ModelMap();

		log.debug("编辑内容参数! contentId= {}, content = {}", contentId, content);

		content.setId(contentId);
		contentService.saveOrUpdate(content);
		log.info("编辑内容成功! contentId= {}, content = {}", contentId, content);
		messagesMap.put("status", SUCCESS);
		messagesMap.put("message", "编辑成功!");
		return messagesMap;
	}

	/**
	 * 检验内容名是否存在
	 *
	 * @param id
	 * @param name
	 * @return
	 */
	@ResponseBody
	@GetMapping(value = "/isExist")
	public Boolean isExist(Long id, String name) {
		boolean flag = true;
		log.debug("检验内容名称是否存在参数! id= {}, name= {}", id, name);

		Content record = contentService.findByName(name);
		if (null != record && !record.getId().equals(id)) {
			flag = false;
		}
		log.info("检验内容名称是否存在结果! flag = {}", flag);
		return flag;
	}

}
